<?php
namespace api\action\voteplayer;

use Yii;
use yii\rest\IndexAction as BaseIndexAction;
use yii\data\ActiveDataProvider;
use yii\data\DataFilter;

class IndexAction extends BaseIndexAction
{
    public function init()
    {
        parent::init();

        $this->dataFilter = [
            'class' => 'yii\data\ActiveDataFilter',
            'searchModel' => function () {
                return (new \yii\base\DynamicModel(['vid' => null]))
                    ->addRule('vid', 'string');
            },
            'filter' => ['vid' => Yii::$app->request->get('vid')]
        ];

    }


    protected function prepareDataProvider()
    {
        $requestParams = Yii::$app->getRequest()->getBodyParams();
        if (empty($requestParams)) {
            $requestParams = Yii::$app->getRequest()->getQueryParams();
        }

        $filter = null;
        if ($this->dataFilter !== null) {
            $this->dataFilter = Yii::createObject($this->dataFilter);
            if ($this->dataFilter->load($requestParams)) {
                $filter = $this->dataFilter->build();
                if ($filter === false) {
                    return $this->dataFilter;
                }
            }
        }


        /* @var $modelClass \yii\db\BaseActiveRecord */
        $modelClass = $this->modelClass;

        $query = $modelClass::find();
        if (!empty($filter)) {
            $query->andWhere($filter);
        }



        return Yii::createObject([
            'class' => ActiveDataProvider::className(),
            'query' => $query,
            'pagination' => [
                'params' => $requestParams,
                'pageSize' => 30 
            ],
            'sort' => [
                'params' => $requestParams,
            ],
        ]);
    }

}
